<template>
	<view v-if="detail.pk_id">
		<sww-swipe :list="swipeList" indicatorDots autoplay></sww-swipe>
		<view class="form_main">
			<view class="summary_desc" v-if="parameter.summary">{{ parameter.summary }}</view>
			<view class="form_item" v-if="parameter.SubmitForm.username > 0">
				<view class="title"><text style="color: #F34D4E;">*</text>姓名</view>
				<input class="input input_view" type="text" v-model="subForm.userName" placeholder="请输入您的姓名"/>
			</view>
			<view class="form_item" v-if="parameter.SubmitForm.phone > 0">
				<view class="title"><text style="color: #F34D4E;">*</text>电话</view>
				<input class="input input_view" type="number" v-model="subForm.phone" placeholder="请输入您的电话"/>
			</view>
			<view class="form_item" v-for="(item, index) in detail.option" :key="index">
				<image v-if="item.componentName == 'FormAdvert'" :src="item.value" mode="widthFix" class="form_advert"></image>
				<template v-else-if="item.componentName == 'tipText'">
					<view class="tip_text" v-if="item.value">{{ item.value }}</view>
				</template>
				<template v-else-if="!item.businessEdit">
					<view class="title"><text v-if="item.required" style="color: #F34D4E;">*</text> {{ item.title }}</view>
					<template v-if="item.componentName == 'FormInput'">
						<!-- 听说H5不能动态变type -->
						<input class="input input_view" v-if="item.inputType == 1 || item.inputType == 3" type="number" v-model="item.value" :placeholder="'请输入' + item.title"/>
						<view v-else class="input input_flex">
							<input class="input_in" type="text" v-model="item.value" :placeholder="'请输入' + item.title"/>
							<view @click="getAddress(index)" v-if="item.inputType == 2" class="iconfont iconfont-e769"></view>
						</view>
					</template>
					<template v-else-if="item.componentName == 'FormTextarea'">
						<textarea class="input input_textarea" type="textarea" v-model="item.value" />
					</template>
					<template v-else-if="item.componentName == 'FormTime' || item.componentName == 'dateTime' || item.componentName == 'FormDate'">
						<form-time v-model="item.value" :mode="item.componentName"></form-time>
					</template>
					<template v-else-if="item.componentName == 'FormRadio'">
						<radio-item v-model="item.value" :options="item.options"></radio-item>
					</template>
					<template v-else-if="item.componentName == 'FormCheckbox'">
						<checkbox-item v-model="item.value" :options="item.options"></checkbox-item>
					</template>
					<template v-else-if="item.componentName == 'uploadImg'">
						<upload-item v-model="item.value" :inputType="item.inputType"></upload-item>
					</template>
				</template>
			</view>
			<view class="pay_box" v-if="detail.price > 0">
				<view class="title">参与人数</view>
				<u-number-box :min="1" v-model="buyNum"></u-number-box>
			</view>
		</view>
		<view class="glo_bot_main">
			<view class="glo_bot_fix">
				<view class="glo_button" @click="startSubmit" :style="{ background: vuex_config.themeColor1 }">
					提交
					<template v-if="detail.price > 0">
						<text class="sign">￥</text>
						<text class="price_total">{{ (detail.price * buyNum).toFixed(2) }}</text>
					</template>
				</view>
			</view>
		</view>
		<sww-pay-class ref="payCheck" @callBack="onPayPrice"></sww-pay-class>
	</view>
</template>

<script>
import radioItem from '../components/radioItem.vue';
import checkboxItem from '../components/checkboxItem.vue';
import uploadItem from '../components/uploadItem.vue';
import formTime from '../components/formTime.vue';
import { isMobile, landline,idCard } from '@/utils/validate.js';
import { payOrder } from '@/mixins/payOrder.js';
import { wxConfig } from '@/mixins/wxConfig';
import { authorize } from '@/utils/uniPromise.js';
export default {
	mixins: [payOrder, wxConfig],
	props: {
		formId: {
			type: Number,
			default: 0
		},
		canSub:{
			type:Boolean,
			default:true
		},// 是否在可提现时间段内
	},
	components: {
		radioItem,
		checkboxItem,
		'upload-item': uploadItem,
		formTime
	},
	data() {
		return {
			detail: {},
			validateForm: {
				FormInput: {
					reg: (item)=>{
						let valid = true
						let msg = ''
						if(item.inputType == 3){
							valid = isMobile(item.value)
							msg = valid?'':'请输入正确的手机号'
						}else if(item.inputType == 4){
							valid = idCard(item.value)
							msg = valid?'':'请输入正确的身份证号码'
						}
						return {
							valid:valid,
							msg:msg
						}
					}
				}
			},
			buyNum: 1,
			paramsArr: [],
			parameter: {},
			swipeList: [],
			subForm: {
				userName: '',
				phone: ''
			}
		};
	},
	mounted() {
		// #ifdef H5
		this.initWxConfig(['chooseWXPay'])
			.then(() => {})
			.catch(() => {});
		// #endif
		this.$initPage();
	},

	methods: {
		$initPage() {
			this.$loading();
			this.$resPost('GetCustomFormInfo', { pk_id: this.formId }).then(({ data }) => {
				if (!data.pk_id) {
					this.$hide();
					uni.showModal({
						title: '提示',
						content: '活动已结束',
						showCancel: false,
						success: res => {
							this.uniBack();
						}
					});
					return;
				}
				uni.setNavigationBarTitle({
					title: data.name
				});
				let arr = JSON.parse(data.option);
				this.parameter = JSON.parse(data.parameter);
				this.$emit('initAdd',{...this.parameter})
				if (this.parameter.img) {
					this.swipeList = this.parameter.img.split(',').map(item => {
						return {
							img: item
						};
					});
				}
				this.detail = {
					...data,
					option: arr,
					parameter: ''
				};
				this.$hide();
			});
		},
		// 打开地图，选择地址
		getAddress (index) {
			authorize('scope.userLocation')
				.then(() => {
				uni.chooseLocation({
					success: (res)=> {
						this.detail.option[index].value = res.address
					}
				})
			})
		},
		// 点击提交
		startSubmit() {
			this.$login('resetLogin').then(() => {
				if(!this.canSub){
					let str = this.parameter.subTime.replace(',','-')
					this.$toast(`请在以下时间内提交：${str}`)
					return
				}
				this.judgeSubAdnOrder()
					.then(() => {
						this.sureSubmit();
					})
					.catch(() => {});
			});
		},
		// 判断能否提交且是否需要支付,不需要支付 回调 resolve()
		judgeSubAdnOrder() {
			return new Promise((resolve, reject) => {
				if (this.parameter.SubmitForm.username > 0 && !this.subForm.userName) {
					this.$toast({ title: '请填写用户姓名' });
					reject();
					return;
				}
				if (this.parameter.SubmitForm.phone > 0) {
					if (!this.subForm.phone) {
						this.$toast({ title: '请填写联系电话' });
						reject();
						return;
					} else if (!isMobile(this.subForm.phone) && !landline(this.subForm.phone)) {
						this.$toast({ title: '请填写正确的电话' });
						reject();
						return;
					}
				}

				let str = '';
				let paramsArr = [];
				let index = this.detail.option.findIndex(item => {
					if (!item.businessEdit && item.required && !item.value) {
						str = item.title + '不能为空';
						return true;
					} else if (this.validateForm[item.componentName] && item.value) {
						let obj = this.validateForm[item.componentName].reg(item)
						if (!obj.valid) {
							str = obj.msg;
							return true;
						}
					}
					paramsArr.push({
						businessEdit: item.businessEdit,
						componentName: item.componentName,
						options: item.options,
						title: item.title,
						value: item.value
					});
					return false;
				});
				if (str) {
					this.$toast({ title: str });
					reject();
					return;
				}
				this.paramsArr = [].concat(paramsArr);
				if (this.detail.price > 0) {
					this.$refs.payCheck.open(this.buyNum * this.detail.price);
					reject();
				} else {
					resolve();
				}
			});
		},
		// 提交
		/**
		 * isOrder 是否需要支付
		 * */
		sureSubmit(isOrder) {
			this.$loading();
			return new Promise((resolve, reject) => {
				let params = {
					custom_form_id: this.detail.pk_id
				};
				if (this.subForm.userName) {
					params.name = this.subForm.userName;
				}
				if (this.subForm.phone) {
					params.phone = this.subForm.phone;
				}
				if(this.parameter.examine == 1){
					params.status = 1
				}
				this.$resPost('SetCustomFormInfo', params, JSON.stringify(this.paramsArr))
					.then(res => {
						if (!isOrder) {
							this.$hide();
							this.$toast({ title: '提交成功', icon: 'success' });
							setTimeout(() => {
								this.$emit('subFinsh', true);
							}, 800);
						}
						resolve(res.data);
					})
					.catch(() => {
						reject();
					});
			});
		},
		// 确定支付
		onPayPrice(e) {
			let pay_type = e.pay_type
			let params = {
				business_appid: this.vuex_business.appid,
				total_amount: (this.buyNum * this.detail.price).toFixed(2),
				remark: '自定义表单订单'
			};
			let options = {
				orderApi: 'AddOrderForm',
				redirectUrl: '',
				totalPrice: params.total_amount,
				pay_type: pay_type,
				order_type: 13,
				remark: '自定义表单订单'
			};
			// 下单前准备工作
			this._submitOrder({}, { modal: false, createAble: false })
				.then(data => {
					// 提交表单内容
					this.sureSubmit(true).then(valId => {
						let json_detailed = [
							{
								fk_form_id: valId,
								price: this.detail.price,
								num: this.buyNum,
								remark: '表单支付'
							}
						];
						// 生成订单并支付
						this.createOrder({ ...params, json_detailed: JSON.stringify(json_detailed) }, { ...data, ...options })
							.then(res => {
								this.$toast({ title: '提交成功', icon: 'success' });
								setTimeout(() => {
									this.$emit('subFinsh', true);
								}, 1000);
							})
							.catch(() => {
								setTimeout(() => {
									this.$emit('subFinsh');
								}, 800);
							});
					});
				})
				.catch(() => {});
		},
		// 提交前才登录
		resetLogin() {
			this.$emit('resetLogin');
		}
	}
};
</script>
<style scoped lang="scss">
.form_main {
	padding: 0 24rpx 1rpx;
	background-color: #fff;
	.summary_desc {
		white-space: pre-wrap;
		padding: 20rpx 10rpx 0;
		font-size: 28rpx;
		color: #484848;
	}
}
.form_item {
	padding-bottom: 10rpx;
	.form_advert {
		width: 100%;
	}
	.tip_text {
		font-weight: bold;
		font-size: 30rpx;
	}
	.title {
		font-weight: bold;
		padding: 30rpx 0;
	}
	.input {
		border: 1px solid #dde5ed;
		border-radius: 6rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		margin-bottom: 30rpx;
		&.input_view {
			line-height: 68rpx;
			height: 68rpx;
		}
		&.input_textarea {
			width: 100%;
			padding: 10rpx 20rpx;
			line-height: 42rpx;
			height: 168rpx;
		}
	}
	.input_flex{
		display: flex;
		align-items: center;
		.input_in {
			flex: 1;
			overflow: hidden;
			line-height: 68rpx;
			height: 68rpx;
		}
		.iconfont{
			font-size: 34rpx;
			padding-left: 16rpx;
			line-height: 60rpx;
		}
	}
}
.pay_box {
	padding-bottom: 40rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.sign {
	font-size: 26rpx;
}
</style>
